package com.liusand.admin.controller;

import com.liusand.admin.service.CategoryService;
import com.liusand.xo.common.Result;
import com.liusand.xo.pojo.Category;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author LiuSha
 */
@RestController
@RequestMapping("category")
@Slf4j
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @PostMapping("add")
    public Result add(@RequestBody Category category){
        if(category.getCategoryName() == null || category.getCategoryName().length() > 20 || category.getCategoryName().length() == 0){
            log.info("分类名称\"{}\"不得高于20个字且不能为空", category.getCategoryName());
            return Result.error("分类名称" + category.getCategoryName() + "不得高于20个字且不能为空");
        }
        boolean status = categoryService.add(category);
        if(!status) {
            return Result.error();
        }
        Category newCategory = categoryService.findByName(category.getCategoryName());
        return Result.success(newCategory);
    }

    @GetMapping("findAll")
    public Result findAll(){
        List<Category> categories = categoryService.findAll();
        if(categories == null){
            return Result.error();
        }
        return Result.success(categories);
    }

    @GetMapping("findById/{id}")
    public Result findById(@PathVariable String id){
        if(id == null || id.length() == 0){
            return Result.error();
        }
        Category category = categoryService.findById(id);
        if(category == null){
            return Result.error();
        }
        return Result.success(category);
    }

    @DeleteMapping("delete/{id}")
    public Result delete(@PathVariable String id){

        boolean result = categoryService.deleteById(id);

        if(!result){
            return Result.error();
        }
        return Result.success();
    }

    @PutMapping("update")
    public Result update(@RequestBody Category category){
        if(category.getCategoryName() == null || category.getCategoryName().length() > 20 || category.getCategoryName().length() == 0){
            log.info("分类名称\"{}\"不得高于20个字且不能为空", category.getCategoryName());
            return Result.error();
        }
        boolean result = categoryService.update(category);
        if(!result){
            return Result.error();
        }
        return Result.success();
    }
}
